package com.gzgy.ustore.api.inteceptors;

import org.apache.commons.logging.Log;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Created by jancekyang on 2017/7/14.
 */
public class InteceptorUtil {

    public static void printParamLog(Log logger, HttpServletRequest request){
        //打印log
        try {

            Enumeration<?> names = request.getParameterNames();

            String uri = request.getRequestURI();
            StringBuilder logInfo = new StringBuilder();
            logInfo.append(uri).append("?");

            while (names.hasMoreElements()) {
                String name = (String) names.nextElement();
                if(name.equals("userPwd")){

                    logInfo.append(name).append("=").append("******").append("&");
                }else{
                    String[] values = request.getParameterValues(name);

                    logInfo.append(name).append("=").append(ararryToString(values)).append("&");
                }
            }

            logger.info(logInfo);

        } catch (Exception e) {
            logger.info(e.getMessage());
        }
    }


    /**
     * 功能描述：输出数组,枨式为[value1 ; value2 ; .......]
     *
     * @param values
     * @return
     */
    private static String ararryToString(String[] values) {
        if (values == null) {
            return null;
        }

        StringBuilder result = new StringBuilder();

        if (values.length > 1) {
            result.append("[");
        }

        for (String value : values) {

            String shortValue = value;
            if (result.length() > 0) {
                result.append(" ; ").append(shortValue);
            } else {
                result.append(shortValue);
            }
        }

        if (values.length > 1) {
            result.append("]");
        }

        return result.toString();
    }
}
